<template>
  <div class="year-detail">
    <div>
      <el-card>
        <div style="text-align: right;">
          <el-button type="primary" size="mini" style="margin-top:-10px;margin-right:10px" @click="addNewMonth">新建月计划</el-button>
        </div>
        <div class="space-between" style="display: flex">
          <span style="font-weight: bold;line-height: 40px">当前计划:{{oneYearData.planTime}}{{oneYearData.draftName}}</span>
          <div>
            今天：{{today}}
            <el-button type="primary" size="mini" style="margin-top:10px;margin-right:10px" plain @click="toDetailPlan(oneYearData.planTime,oneYearData.draftStatus)">详情</el-button>
          </div>
        </div>
        <circle-compent :detailCatagrayCount="oneYearData.monthPlanAmount/10000" :detailProductCount="oneYearData.monthFinishRatioString"
                        :detailOffLine="oneYearData.categoryNumber" :percent="oneYearData.productCodeNumber" :titleName="titleName"></circle-compent>
      </el-card>
      <div style="margin-top: 25px">
        <el-select v-model="yearSet" @change="renderCharts" size="mini" placeholder="请选择">
          <el-option v-for="(item,index) in 10"
                     :key="index" :label="`${currentYear-item+1}年`" :value="(currentYear-item+1)">
          </el-option>
        </el-select>
        <el-radio-group  size="mini" v-model="saleType" @change="saleSelect">
          <el-radio-button label='0'>销额</el-radio-button>
          <el-radio-button label="1">销量</el-radio-button>
        </el-radio-group>
      </div>
      <div id="saleSummaryChart" style="height: 300px;width:100%;margin:10px"></div>
      <br><br>
      <span >创建时间</span>
      <el-date-picker style="width: 300px" size="mini" type="daterange"
                      value-format="yyyy-MM-dd" :picker-options="pickerOptions" range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期">
      </el-date-picker>
      <el-select size="mini" style="width: 100px" placeholder="请选择" v-model="yearTime" @change="getdrafts">
        <el-option v-for="(n,index) in 20" :key="index"
                   :label="currentYear-10+n-1" :value="currentYear-10+n-1">
        </el-option>
      </el-select>
      <el-table size="mini" :data="twoPageTable" style="width: 100%;margin-top:20px">
        <el-table-column
          prop="draftName"
          label="月计划">
          <template slot-scope="scope">
            <span>{{scope.row.planTime}}{{scope.row.draftName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.draftStatus == '0'" >草案</span>
            <span v-else >计划</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="monthPlanAmount"
          :formatter="formatterColumn"
          :sort-method="sortMonthPlanAmount"
          sortable
          label="计划销额(万元)">
        </el-table-column>
        <el-table-column
          prop="monthFinishRatioString"
          :sort-method="sortmonthFinishRatioString"
          label="完成度"
          sortable>
        </el-table-column>
        <el-table-column
          prop="categoryNumber"
          label="品类数(个)">
        </el-table-column>
        <el-table-column
          prop="productCodeNumber"
          label="产品数(个)">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          sortable>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.draftStatus == '0'">
              <el-button type="text" @click="deleteDraftByDraftId(scope.row.draftId)">删除</el-button>
              <el-button type="text" @click="draftToEdit(scope.row.planTime,scope.row.draftStatus)">详情/发布</el-button>
            </div>
            <el-button v-else type="text"  @click="toDetailPlan(scope.row.planTime,scope.row.draftStatus)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import * as opreate from 'api/getData'
  import CircleCompent from 'router/marketSale/compentSet/circleCompent'
  let currentYear = new Date().getFullYear()

  export default {
    name: "mon",
    data(){
      return{
        pickerOptions:{
          disabledDate: this.limitSet
        },
        dataPicker:'',
        yearSet:new Date().getFullYear(),
        currentYear: currentYear,
        oneYearData: {},
        twoPageTable:[],
        mainchart:'',
        titleName:[
          '月计划销额（万元）',
          '月销额完成度',
          undefined,
          '品类数（个）',
          '产品数（个）'
        ],
        yearTime:new Date().getFullYear(),
        monthTime:new Date().format('MM'),
        today:new Date().format("yyyy-MM-dd"),
        saleType:0,
        myChart:'',
        checkMonthPlan:''
      }
    },
    components:{
      CircleCompent
    },
    mounted(){
      this.getDetail(`${this.yearTime}-${this.monthTime}`,1)
      this.getdrafts(this.yearTime)
    },
    methods:{
      formatterColumn(row, column){
        return ((row.monthPlanAmount || 0)/10000).toFixed(2)
      },
      sortMonthPlanAmount(prev,next){
        return parseFloat(prev.monthPlanAmount || '0') - parseFloat(next.monthPlanAmount || '0')
      },
      sortmonthFinishRatioString(prev,next){
        return parseFloat(prev.monthFinishRatioString || '0') - parseFloat(next.monthFinishRatioString || '0')
      },
      addNewMonth() {
        localStorage.removeItem('editMonth')
        localStorage.removeItem('editDid')
        this.$router.push({ name:'newMonthPlan' })
      },
      limitSet: function(time) {
        return time.getTime() < new Date(this.yearTime,1,1).getTime() || time.getTime() > new Date(this.yearTime,12,31).getTime()
      },
      draftToEdit(monthPlan, draftStatus){
        this.$router.push({
          name:'editMonthPlan',
          params: { monthPlan, draftStatus }
        })
      },
      toDetailPlan(monthPlan,draftStatus){
        this.$router.push({
          name:'monthProdList',
          params: { monthPlan, draftStatus }
        })
      },
      planSelect(){
        this.getdrafts(this.yearTime)
      },
      backSet(){
        this.$router.back(-1)
      },
      deleteDraftByDraftId (draftId) {
        this.$confirm('确认删除该草案？').then(_ => {
          opreate.deleteDraftById({ draftId }).then(res => {
            if(res.code == '200'){
              this.getdrafts(this.yearTime)
              this.$message.success('删除成功')
            }else {
              this.$message.success('操作失败')
            }
          }) .catch(err => {})
        })
      },
      getDetail(monthPlanTime, draftStatus){ // status:1计划，0草案
        opreate.getMonthPlan({ monthPlanTime,draftStatus }).then(res => {
          this.oneYearData = res.data || {}
          this.renderCharts(this.yearSet)
        })
      },
      getdrafts(yearPlanTime){
        let [ firstTime,lastTime ] =this.dataPicker
        opreate.getMonthPlanAll({
          yearPlanTime,
          firstTime,
          lastTime
        }).then(res => {
          this.twoPageTable = res.data
        })
      },
      saleSelect(){
        '0' == this.saleType ? this.saleAUpdate() : this.saleCUpdate()
      },
      renderCharts(dateTime) {
        opreate.getSaleMonthData({ dateTime }).then(res => {
          let [ mainchart = [] ] = res.data || {}
          this.mainchart = mainchart
          '0' == this.saleType ? this.saleAUpdate() : this.saleCUpdate()
        })
      },
      saleAUpdate(){
        if(document.getElementById('saleSummaryChart')){
          this.myChart = this.$echarts.init(document.getElementById('saleSummaryChart'))
          let option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                crossStyle: {
                  color: '#999'
                }
              },
              formatter:(param) => {
                let [ A = {}, B = {}, C = {}, D = {} ] = param
                let totalSet = Boolean(Number(B.data)) ? (Number(A.data || 0) -  Number(B.data || 0)).toFixed(2) : (Number(A.data || 0) +  Number(C.data || 0)).toFixed(2)
                let tipSet = (A.axisValue || '') +'<br/>'+'实际销额:'+ (A.data || 0) +'万<br/>'+'计划销额:'+ totalSet +'万<br/>'+'月环比:'+ (D.data|| '')+'%'
                return tipSet
              }
            },
            legend: {
              data:['实际销额','销额超出计划','销额低于计划','销额环比'],
              right:20
            },
            xAxis: [
              {
                type: 'category',
                data: this.mainchart.map(item => item.dateTime)
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '销售额(万元)',
                axisLabel: {
                  formatter: '{value} '
                }
              },
              {
                type: 'value',
                name: '环比',
                axisLabel: {
                  formatter: '{value}% '
                }
              }
            ],
            series: [
              {
                name:'实际销额',
                type:'bar',
                itemStyle: {
                  color: '#aa94dc'
                },
                stack:'ss',
                barMaxWidth: '25px',
                data:this.mainchart.map(item => {
                  return ((Number(item.actualSalesAmount))/10000).toFixed(2)
                })
              },
              {
                name:'销额超出计划',
                type:'bar',
                itemStyle: {
                  color: '#ee87a7'
                },
                barMaxWidth: '25px',
                stack:'ss',
                data:this.mainchart.map(item => {
                  return ((Number(item.salesAmountHigherThanPlanData || 0))/10000).toFixed(2)
                 })
              },
              {
                name:'销额低于计划',
                type:'bar',
                itemStyle: {
                  color: '#64bef5'
                },
                barMaxWidth: '25px',
                stack:'ss',
                data:this.mainchart.map(item => {
                  return ((Number(item.salesAmountLowerThanPlannData || 0))/10000).toFixed(2)
                })
              },
              {
                name:'销额环比',
                type:'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#64bef5'
                },
                data:this.mainchart.map(item => {
                  return item.actualSalesAmountRingRatio || '0.00'
                })
              }
            ]
          };
          this.myChart.clear();
          this.myChart.setOption(option); // 使用刚指定的配置项和数据显示图表
        }
      },
      saleCUpdate(){
        let option = {
          tooltip: {
            show:true,
            trigger: 'axis',
            formatter:(param) => {
              let [ A = {}, B = {}, C = {}, D = {} ] = param
              let totalSet = Boolean(Number(B.data)) ? (Number(A.data || 0) -  Number(B.data || 0)).toFixed(0) : (Number(A.data || 0) +  Number(C.data || 0)).toFixed(0)
              let tipSet = (A.axisValue || '') +'<br/>'+'实际销量:'+ (A.data || 0) +'<br/>'+'计划销量:'+ totalSet +'<br/>'+'月环比:'+ (D.data|| '')+'%'
              return tipSet
            }
          },
          legend: {
            data:['实际销量','销量超出计划','销量低于计划','销量环比'],
            right:20
          },
          xAxis: [
            {
              type: 'category',
              data: this.mainchart.map(item => item.dateTime)
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '销售量(件)',
              axisLabel: {
                formatter: '{value} '
              }
            },
            {
              type: 'value',
              name: '环比',
              axisLabel: {
                formatter: '{value}% '
              }
            }
          ],
          series: [
            {
              name:'实际销量',
              type:'bar',
              itemStyle: {
                color: '#aa94dc'
              },
              barMaxWidth: '25px',
              stack:'ss',
              data:this.mainchart.map(item => item.actualSalesCount || 0),
            },
            {
              name:'销量超出计划',
              type:'bar',
              itemStyle: {
                color: '#ee87a7'
              },
              barMaxWidth: '25px',
              stack:'ss',
              data:this.mainchart.map(item => item.salesCountHigherThanPlanData || 0),
            },
            {
              name:'销量低于计划',
              type:'bar',
              itemStyle: {
                color: '#64bef5'
              },
              barMaxWidth: '25px',
              stack:'ss',
              data:this.mainchart.map(item => item.salesCountLowerThanPlannData || 0),
            },
            {
              name:'销量环比',
              type:'line',
              smooth: true,
              yAxisIndex: 1,
              itemStyle: {
                color: '#64bef5'
              },
              data:this.mainchart.map(item => item.actualSalesCountRingRatio || '0.00')
            },
          ]
        };
        this.myChart.clear();
        this.myChart.setOption(option); // 使用刚指定的配置项和数据显示图表
      }
    }
  }
</script>

<style scoped>

</style>

